/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bwi_test_node;

import com.sarco.bwi.lib.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author iktsup
 */
public class Main {

    private static String blenderPath;
    private static String file;
    private static int startFrame;
    private static int endFrame;
    private static String path;
    private static String format;
    private static int addFileExt;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            InputStream in;

            boolean canStart = false;

            Config conf = new Config();
            conf.loadConfig("default.config");

            System.out.println("Connecting!");
            Socket client = new java.net.Socket(conf.master, conf.port);
            System.out.println("Connected!");

            Main.blenderPath = conf.blenderPath;
            Main.file = conf.blend;
            Main.startFrame = conf.startFrame;
            Main.endFrame = conf.endFrame;
            Main.path = conf.ouput;
            Main.format = conf.format;
            Main.addFileExt = 1;
            
            in = client.getInputStream();

            

            while (!canStart) {
                System.out.println("Waiting for COMMAND!");
                String s = "";
                byte[] bIn = new byte[128];
                in.read(bIn);

                for (int y = 0; y < bIn.length; y++) {
                    s += (char) bIn[y];
                }
                System.out.println(s);
                if (s.startsWith(Node.MASTER_SHARE_JOBS)) {
                    s = s.substring(Node.MASTER_SHARE_JOBS.length());
                    String[] frames = s.split(Node.COMMON_SPLIT);
                    Main.startFrame = Integer.parseInt(frames[0]);
                    Main.endFrame = Integer.parseInt(frames[1]);
                    canStart = true;
                }
            }

            com.sarco.bwi.lib.Blender blender = new com.sarco.bwi.lib.Blender(
                    blenderPath, file, startFrame, endFrame, path, format,
                    addFileExt, client);

            blender.render();
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } /* catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } */
    }
}
